package com.cwd.arm.application.service.write;

import com.cwd.arm.application.dto.role.RoleAddDto;
import com.cwd.arm.application.dto.role.RoleUpdateDto;
import com.cwd.arm.application.service.write.facade.RoleWriteService;
import com.cwd.arm.common.dto.session.AuthDto;
import com.cwd.arm.domain.entity.AuthEntity;
import com.cwd.arm.domain.entity.RoleEntity;
import com.cwd.arm.domain.repository.RoleRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
* Description:角色
* Created on 2021年11月16日
* @author  yan
*/
@Repository
@Primary
public class RoleWriteServiceImpl implements RoleWriteService{

    @Autowired
    private RoleRepository roleRepository;

    @Transactional
    @Override
    public void save(RoleAddDto addDto) {
        roleRepository.save(convertToEntity(addDto));
    }

    @Transactional
    @Override
    public void update(RoleUpdateDto updateDto) {
        roleRepository.update(convertToEntity(updateDto));
    }

    @Transactional
    @Override
    public void del(Long id) {
        roleRepository.del(id);
    }

    private RoleEntity convertToEntity(RoleAddDto dto){
        RoleEntity roleEntity = new RoleEntity();
        BeanUtils.copyProperties(dto,roleEntity);
        return roleEntity;
    }

    private RoleEntity convertToEntity(RoleUpdateDto dto){
        RoleEntity roleEntity = new RoleEntity();
        BeanUtils.copyProperties(dto,roleEntity);
        roleEntity.setBtnAuthList(convertToAuthEntityList(dto.getBtnAuthList()));
        roleEntity.setMenuAuthList(convertToAuthEntityList(dto.getMenuAuthList()));
        return roleEntity;
    }

    private List<AuthEntity> convertToAuthEntityList(List<AuthDto> authDtoList){
        if(authDtoList == null){
            return null;
        }
        return authDtoList.stream().map(dto->(convertToAuthEntity(dto))).collect(Collectors.toList());
    }

    private AuthEntity convertToAuthEntity(AuthDto authDto){
        AuthEntity authEntity = new AuthEntity();
        BeanUtils.copyProperties(authDto,authEntity);
        return authEntity;
    }

}
